package com.travel.carmen;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


/**
	Save Notes for the Travel Mobile Application Carmen.
	 The View is the Save Interface (layout as per save.xml) for the application.
	 Provides users with an overview of the note to be saved as a new note or an edit
	 of an existing note from a user account. Fields to be filled or edited for users
	 is the Category and Title. The Edit Text Boxes are labeled with the language
	 selections made in the Main Interface. To save notes, a valid user account is required.
	 Requests are made through XMLRPC service calls.
   	@author Arturo Aparicio 
   	@author Edwin Boykin 
   	@author Veena Chengalnaidu
   	@author Anton Ganeshalingam
   	@author Lakshmi Mallampati
   	@author Tarun Morton
   	@author Chantha Thoeun
*/
public class Save extends Activity implements OnClickListener
{
	// Identifiers
	
	private EditText titleEditText;
	private Spinner categorySpinner;
	private EditText noteFromEditText;
	private EditText noteToEditText;
	private TextView lang_src_tv;
	private TextView lang_tar_tv;
	private Button saveButton;
	private boolean saved = false;
	private String username;
	private String password;
	private String lang_src;
	private String lang_tar;
	private int nid;
	
	// Default Category Spinner position
	private static final int CONVERSATION = 1;
	
	// ProgressDialog
	private ProgressDialog dialog;
	
	@Override
	/**
	   Called when the activity is first created.
	    The UI activities as per save.xml are inflated.
	    All listeners and adapters are attached and all settings are
	    made to default.
	 */
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.save);
		
		username = getIntent().getStringExtra(getString(R.string.username));
		password = getIntent().getStringExtra(getString(R.string.password));
		String noteToSave = getIntent().getStringExtra(getString(R.string.to_save_note));
		String transToSave = getIntent().getStringExtra(getString(R.string.trans_to_save_note));
		String titleToSave = getIntent().getStringExtra(getString(R.string.title));
		int categorySpinnerPosition = getIntent().getIntExtra(getString(R.string.select_category), 
				CONVERSATION);
		lang_src = getIntent().getStringExtra(getString(R.string.lang_src));
		lang_tar = getIntent().getStringExtra(getString(R.string.lang_tar));
		nid = getIntent().getIntExtra(DrupalNode.NID, DrupalNode.INVALID_NID);	
		Log.d("NID", ""+nid);
		
		titleEditText = (EditText) findViewById (R.id.TitleEditText);
		categorySpinner = (Spinner) findViewById(R.id.category_selection);
		noteFromEditText = (EditText) findViewById(R.id.NoteFromEditText);
		noteToEditText   = (EditText) findViewById(R.id.NoteToEditText);
		saveButton = (Button) findViewById(R.id.save_button);
		lang_src_tv = (TextView) findViewById(R.id.lang_src_textview);
		lang_tar_tv = (TextView) findViewById(R.id.lang_tar_textview);
		
		if (nid != DrupalNode.INVALID_NID)
			saveButton.setText("Save Edit");
		
		// Set TextView labels
		lang_src_tv.setText(lang_src + ":");
		lang_tar_tv.setText(lang_tar + ":");
		
		//Used to populate notes
		ArrayAdapter categories = ArrayAdapter.createFromResource(this, 
				R.array.categories, android.R.layout.simple_spinner_item);
		categories.setDropDownViewResource(
				android.R.layout.simple_spinner_dropdown_item);
		
		categorySpinner.setAdapter(categories);	
		// set to default as per web site
		categorySpinner.setSelection(categorySpinnerPosition);
		noteFromEditText.setText(noteToSave);
		noteToEditText.setText(transToSave);
		if (titleToSave != null)
			titleEditText.setText(titleToSave);
		noteFromEditText.setFocusable(false);
		noteToEditText.setFocusable(false);
		saveButton.setOnClickListener(this);
		
		dialog = new ProgressDialog(this);
		dialog.setMessage("Saving note...");
		dialog.setIndeterminate(true);
	}

	@Override
	/**
	   Listener for Save. A Pre check is done to prompt for title if
	    the Title field is blank (Saving New Notes). Default Category
	    for new notes is Conversation as per the settings on the 
	    Carmen (Drupal) Website.
	   @param v the View for this Listener
	 */
	public void onClick(View v) 
	{
		String title = titleEditText.getText().toString();
		if (title.equals(Main.BLANK))
			Toast.makeText(getApplicationContext(), 
					"Please Enter a Title", 1).show();
		else
		{	
			dialog.show();
			Thread thread = new Thread() 
			{
				@Override
				/**
				   Prepares for Note saving utilizing a Java Thread
				 */
				public void run() 
				{
					saveMessage();
					handler.sendEmptyMessage(Main.EMPTY);
				}
			};
			thread.start();
		}
	}
	
	
	/**
	   Handles thread for saving a note. On successful saving, returns
	    Note information and control back to caller. In case of an error,
	    a message is prompted to the user. And the activity remains alive.
	 */
	private Handler handler = new Handler() 
	{
        public void handleMessage(Message msg) 
        {
        	dialog.dismiss();
    		
    		if(saved)
    		{
    			// Finish Activity
    			Intent resultIntent = new Intent();
    			resultIntent.putExtra(getString(R.string.to_save_note), 
    					noteFromEditText.getText().toString());
    			setResult(Activity.RESULT_OK, resultIntent);
    			finish();
    		}  
    		
    		else
    			Toast.makeText(getApplicationContext(), "Unable to Save", 1).show();
        }
	};
	
	
	/**
	   Saves the current Note (and Translation if any) along with all Note
	    information available to the user account. Saving requests are 
	    made through XMLRPC Service calls. This requires a valid Carmen user
	    account.
	 */
	private void saveMessage()
	{
		try 
		{
			
			SharedPreferences settings = getSharedPreferences(
					getString(R.string.app_name), MODE_PRIVATE);
			String apiKey = settings.getString("apiKey", "");
			String serviceDomain = settings.getString("serviceDomain", "");
			String serviceURL = settings.getString("serviceURL", "");
			DrupalXmlRpcService carmenService = 
				new DrupalXmlRpcService(serviceDomain, apiKey, serviceURL);
			carmenService.connect();
			carmenService.login(username, password);
			// delete old node
			if (nid != DrupalNode.INVALID_NID)
			{
				saved = carmenService.nodeDelete(nid);
				Log.d("Save Edit", ""+saved);
			}
    		//setup node
			String title = titleEditText.getText().toString();
    		String category = categorySpinner.getSelectedItem().toString();
    		String note = noteFromEditText.getText().toString();
			DrupalNode toSave = new DrupalNode();
			toSave.setTitle(title);
			toSave.setType(DrupalNode.TYPE_NOTE);
			toSave.setNote(note);
			toSave.setCategory(category);
			toSave.setFromLanguage(lang_src);
			toSave.setToLanguage(lang_tar);
			carmenService.connect();
			saved = carmenService.nodeSave(toSave);
			carmenService.logout();
			Log.d("Save", ""+saved);
			
		}
		catch (Exception e)
		{
			Log.d("Save Failed", e.getMessage());
		}
	}
}
